import { ConfigEnv, UserConfig, defineConfig, loadEnv } from "vite"
import { resolve } from "path"
import { __APP_INFO__ } from "./build/vite/info"
import { createVitePlugins, wrapperEnv } from "./build/vite"
import { __THEME__, themeVar } from "./build/theme/themeVar"

export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
    // 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀
    const env = wrapperEnv(loadEnv(mode, process.cwd(), ""))
    const { VITE_APP_PREFIX, VITE_APP_PORT } = env
    const isBuild = command === "build"

    return {
        base: VITE_APP_PREFIX,
        resolve: {
            alias: [
                {
                    find: "@",
                    replacement: resolve(process.cwd(), "./src")
                },
                {
                    find: "#",
                    replacement: resolve(process.cwd(), "./build")
                }
            ]
        },
        plugins: createVitePlugins(env, isBuild),
        define: {
            __APP_INFO__: JSON.stringify(__APP_INFO__),
            __THEME__: JSON.stringify(__THEME__)
        },
        server: {
            host: true,
            port: VITE_APP_PORT
        },
        css: {
            preprocessorOptions: {
                less: {
                    javascriptEnabled: true,
                    modifyVars: {
                        ...themeVar
                    }
                }
            }
        }
    }
})
